package com.haiheng.voiceandbook.download

import android.util.Log
import com.haiheng.voiceandbook.Constants.Companion.BOOK_PATH
import com.haiheng.voiceandbook.Constants.Companion.ROOT_PATH
import com.haiheng.voiceandbook.MyApplication
import com.haiheng.voiceandbook.common.BookDetailInfoDto
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.net.URL
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit


/**
 * 下载管理
 */
class DownLoadManager {
    companion object {
        private val instance = DownLoadManager()
        fun getInstance(): DownLoadManager {
            return instance;
        }
    }

    /**
     * 停止线程池
     */
    fun shutdown(){
        MyApplication.getInstance().executor.shutdown()
    }
    /**
     * 开始下载任务
     */
    fun startDownLoadTask(list: List<BookDetailInfoDto>) {
        //批量下载
        list.forEach {
            val runnable = DownLoadRunnable(it)
            //执行任务，最多执行核心线程数8，最大线程数8
            MyApplication.getInstance().executor.execute(runnable)
        }

    }

    /**
     * 下载任务
     */
    class DownLoadRunnable(val data: BookDetailInfoDto) : Runnable {

        val TAG = "DownLoadRunnable"
        override fun run() {

            val  name = if ("pdf".equals(data?.bookType)) "${data.bookId}.pdf" else "${data.bookId}.epub"
            val file = File(BOOK_PATH, name)
            if(!file.exists()){
                downLoad(data.path, file, name)
            }
        }

        /**
         * 下载
         */
        private fun downLoad(path: String, file: File, name: String) {
            try {

                Log.e(TAG, "当前线程${Thread.currentThread().name},正在下载${path}")
                val url = URL(path)
                val connection = url.openConnection()
                connection.connect()
                val contentLength: Int = connection.getContentLength()
                val input: InputStream = BufferedInputStream(url.openStream())
                //文件存在，则判断存在的文件大小，如果小于，则是不完整的文件
                if (file.exists())
                {
                    //小于 说明下载不完整
                    if (file.length() < contentLength) {
                        //删掉文件
                        file.delete()
                        //写入文件
                        writeFileToDisk(input, name)
                    }
                }
                //文件不存在直接写入
                else {
                    writeFileToDisk(input, name)
                }

            } catch (e: Exception) {
                Log.e(TAG, "run: ${e}")
            }
        }

        /**
         * 将文件 写入磁盘
         */
        fun writeFileToDisk(input: InputStream, name: String) {
            val file = File(BOOK_PATH, name)
            if (!file.exists()) {
                file.createNewFile()
            }
            try {
                val fos = FileOutputStream(file)
                val bis = BufferedInputStream(input)
                val buffer = ByteArray(1024)
                var len: Int
                var total: Long = 0
                while ((bis.read(buffer).also { len = it } != -1)) {
                    fos.write(buffer, 0, len)
                    total += len
                }
                fos.flush()
                fos.close()
                bis.close()
                input.close()

                Log.e(TAG, "下载完毕${Thread.currentThread().name}")
            } catch (e: Exception) {
                file.delete()
                Log.e(TAG, "writeResponseBodyToDisk: ${e}")
            }
        }
    }
}